package com.jishimed.pocus.androidbledemo;

import android.Manifest;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class MainActivity extends AppCompatActivity implements BleHelper.BTUtilListener,View.OnClickListener {
    private static final String TAG = "MainActivity";
    private static final int REQUEST_LOCATION_PERMISSION = 0;
    BleHelper bleHelper;
    private Button btn_start;
    private ListView list_item;
    List<BluetoothDevice> devices;
    private DevieceAdapter deviceAdapter;
    private TextView tv_info;
    private StringBuffer buffer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);
        btn_start = (Button) findViewById(R.id.btn_start);
        list_item = (ListView) findViewById(R.id.list_item);
        tv_info = (TextView) findViewById(R.id.tv_info);
        btn_start.setOnClickListener(this);
        devices = new ArrayList<>();
        deviceAdapter = new DevieceAdapter(this,devices);
        buffer = new StringBuffer();
        list_item.setAdapter(deviceAdapter);
    }
    @Override
    public void onClick(View v) {
       switch (v.getId()){
           case R.id.btn_start:
               clear();
               //开启位置服务，支持获取ble蓝牙扫描结果
               if (Build.VERSION.SDK_INT >= 23 && !isLocationOpen(getApplicationContext())) {
                   Intent enableLocate = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                   startActivityForResult(enableLocate, REQUEST_LOCATION_PERMISSION);
               }else{
                   testBle();
               }
               break;
       }
    }

    private void clear(){
        devices.clear();
        deviceAdapter.update(devices);
        setMessage("");
    }
    private void testBle(){
        bleHelper = BleHelper.getInstance();
        bleHelper.init(MainActivity.this);
        bleHelper.setBTUtilListener(this);
        bleHelper.scanLeDevice(true);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_LOCATION_PERMISSION) {
            if (isLocationOpen(getApplicationContext())) {
                Log.i("fang", " request location permission success");
                //Android6.0需要动态申请权限
                if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
                        != PackageManager.PERMISSION_GRANTED) {
                    //请求权限
                    ActivityCompat.requestPermissions(this,
                            new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
                                    Manifest.permission.ACCESS_FINE_LOCATION},
                            REQUEST_LOCATION_PERMISSION);
                    if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                            Manifest.permission.ACCESS_COARSE_LOCATION)) {
                        //判断是否需要解释
//                        shortT(getApplicationContext(), "需要蓝牙权限");

                    }
                    testBle();
                }
            } else {
                //若未开启位置信息功能，则退出该应用
                finish();
            }
        }

        super.onActivityResult(requestCode, resultCode, data);

    }
    /**
     * 判断位置信息是否开启
     *
     * @param context
     * @return
     */
    public static boolean isLocationOpen(final Context context) {
        LocationManager manager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
        //gps定位
        boolean isGpsProvider = manager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        //网络定位
        boolean isNetWorkProvider = manager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
        return isGpsProvider || isNetWorkProvider;
    }

    @Override
    public void onLeScanStart() {
        Log.d(TAG, "onLeScanStart: ");
        Toast.makeText(MainActivity.this, "开始扫描", Toast.LENGTH_SHORT).show();
        setMessage("开始扫描");
    }

    @Override
    public void onLeScanStop() {
        Log.d(TAG, "onLeScanStop: ");
        Toast.makeText(MainActivity.this, "停止扫描", Toast.LENGTH_SHORT).show();
        setMessage("停止扫描");
    }

    @Override
    public void onLeScanDevices(List<BluetoothDevice> listDevice) {
        Toast.makeText(MainActivity.this, "扫描完成", Toast.LENGTH_SHORT).show();
        setMessage("扫描完成");
        Log.d(TAG, "onLeScanDevices: listDevice=====" + listDevice.size());
        devices.clear();
        devices.addAll(listDevice);
        deviceAdapter.update(devices);
    }

    @Override
    public void onConnected(BluetoothDevice mCurDevice) {
        Log.d(TAG, "onConnected: mCurDevice=" + mCurDevice);
        setMessage("onConnected");
    }

    @Override
    public void onDisConnected(BluetoothDevice mCurDevice) {
        Log.d(TAG, "onConnected: mCurDevice=" + mCurDevice);
    }

    @Override
    public void onConnecting(BluetoothDevice mCurDevice) {
        Log.d(TAG, "onConnecting: mCurDevice=" + mCurDevice);
    }

    @Override
    public void onDisConnecting(BluetoothDevice mCurDevice) {
        Log.d(TAG, "onDisConnecting: mCurDevice=" + mCurDevice);
    }

    @Override
    public void onStrength(int strength) {
        Log.d(TAG, "onStrength: strength=" + strength);
    }

    @Override
    public void onModel(int model) {
        Log.d(TAG, "onModel: model=" + model);
    }


    public void setMessage(String message){
//        buffer.append(message);
        tv_info.setText("--"+message+"--");
    }
}
